/**
 * MainActivity - 主活动类
 * 
 * 这个类是应用的主界面，用于：
 * - 管理蓝牙连接和权限请求
 * - 显示NeuroSky设备的脑电波数据
 * - 提供设备选择和连接/断开按钮
 * 
 * 使用方法：
 * 1. 启动应用后点击"选择设备连接"按钮
 * 2. 从已配对设备列表中选择要连接的设备
 * 3. 连接成功后实时显示脑电波数据
 * 
 * 原理：
 * - 使用Android蓝牙API进行设备连接
 * - 通过NeuroSkyDataParser解析ThinkGear协议数据
 * - 使用Jetpack Compose构建现代化UI界面
 * - 支持用户手动选择已配对的蓝牙设备进行连接
 */
package com.example.test_bluetooth

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.test_bluetooth.ui.theme.Test_bluetoothTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.InputStream
import java.util.*

class MainActivity : ComponentActivity() {
    
    private var bluetoothAdapter: BluetoothAdapter? = null
    private var bluetoothSocket: BluetoothSocket? = null
    private var inputStream: InputStream? = null
    private var isReconnecting = mutableStateOf(false)
    private var reconnectAttempts = 0
    private val maxReconnectAttempts = 3
    private var currentDevice: BluetoothDevice? = null
    private val neuroSkyParser = NeuroSkyDataParser()
    
    // UI状态变量
    private var isConnected = mutableStateOf(false)
    private var connectionStatus = mutableStateOf("未连接")
    private var attention = mutableStateOf(0)
    private var meditation = mutableStateOf(0)
    private var poorSignal = mutableStateOf(0)
    private var blinkStrength = mutableStateOf(0)
    private var rawValue = mutableStateOf(0)
    private var delta = mutableStateOf(0)
    private var theta = mutableStateOf(0)
    private var lowAlpha = mutableStateOf(0)
    private var highAlpha = mutableStateOf(0)
    private var lowBeta = mutableStateOf(0)
    private var highBeta = mutableStateOf(0)
    private var lowGamma = mutableStateOf(0)
    private var midGamma = mutableStateOf(0)
    
    // 测试用：数据接收日志
    private var dataReceiveLog = mutableStateOf<List<String>>(emptyList())
    private var lastDataTimestamp = mutableStateOf(0L)
    private var dataPacketCount = mutableStateOf(0)
    
    // 新增：设备选择相关状态
    private var availableDevices = mutableStateOf<List<BluetoothDevice>>(emptyList())
    private var showDeviceSelection = mutableStateOf(false)
    private var selectedDevice = mutableStateOf<BluetoothDevice?>(null)

    // 权限请求
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        if (allGranted) {
            initializeBluetooth()
        } else {
            Toast.makeText(this, "需要蓝牙权限才能使用此功能", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置数据解析器回调
        neuroSkyParser.setCallback(object : NeuroSkyDataParser.DataCallback {
            override fun onAttentionUpdate(value: Int) {
                attention.value = value
            }
            
            override fun onMeditationUpdate(value: Int) {
                meditation.value = value
            }
            
            override fun onRawValueUpdate(value: Int) {
                rawValue.value = value
            }
            
            override fun onPoorSignalUpdate(value: Int) {
                poorSignal.value = value
            }
            
            override fun onBlinkUpdate(value: Int) {
                blinkStrength.value = value
            }
            
            override fun onEEGUpdate(delta: Int, theta: Int, lowAlpha: Int, highAlpha: Int,
                                   lowBeta: Int, highBeta: Int, lowGamma: Int, midGamma: Int) {
                this@MainActivity.delta.value = delta
                this@MainActivity.theta.value = theta
                this@MainActivity.lowAlpha.value = lowAlpha
                this@MainActivity.highAlpha.value = highAlpha
                this@MainActivity.lowBeta.value = lowBeta
                this@MainActivity.highBeta.value = highBeta
                this@MainActivity.lowGamma.value = lowGamma
                this@MainActivity.midGamma.value = midGamma
                
                // 测试用：记录数据接收日志
                val currentTime = System.currentTimeMillis()
                this@MainActivity.lastDataTimestamp.value = currentTime
                this@MainActivity.dataPacketCount.value += 1
                
                val logEntry = "数据包 #${this@MainActivity.dataPacketCount.value}: " +
                        "时间=${java.text.SimpleDateFormat("HH:mm:ss.SSS").format(java.util.Date(currentTime))}, " +
                        "注意力=${attention}, 冥想=${meditation}, 信号质量=${200-poorSignal}, " +
                        "Delta=${delta}, Theta=${theta}, Alpha=${lowAlpha+highAlpha}"
                
                val currentLog = this@MainActivity.dataReceiveLog.value.toMutableList()
                currentLog.add(0, logEntry) // 添加到列表开头
                if (currentLog.size > 20) { // 只保留最近20条记录
                    currentLog.removeAt(currentLog.size - 1)
                }
                this@MainActivity.dataReceiveLog.value = currentLog
            }
        })
        
        setContent {
            Test_bluetoothTheme {
                NeuroSkyApp()
            }
        }
        
        checkPermissions()
    }
    
    private fun checkPermissions() {
        val permissions = mutableListOf<String>()
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissions.addAll(listOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.ACCESS_FINE_LOCATION
            ))
        } else {
            permissions.addAll(listOf(
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
            ))
        }
        
        val needPermissions = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }
        
        if (needPermissions.isNotEmpty()) {
            requestPermissionLauncher.launch(needPermissions.toTypedArray())
        } else {
            initializeBluetooth()
        }
    }
    
    private fun initializeBluetooth() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show()
            return
        }
        
        if (bluetoothAdapter?.isEnabled != true) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                startActivity(enableBtIntent)
            }
        }
    }
    
    private fun connectToNeuroSky() {
        // 检查蓝牙适配器
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show()
            return
        }
        
        if (bluetoothAdapter?.isEnabled != true) {
            Toast.makeText(this, "请先开启蓝牙", Toast.LENGTH_SHORT).show()
            return
        }
        
        // 检查权限
        val requiredPermissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            listOf(
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.BLUETOOTH_SCAN
            )
        } else {
            listOf(
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN
            )
        }
        
        val missingPermissions = requiredPermissions.filter {
            ActivityCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }
        
        if (missingPermissions.isNotEmpty()) {
            Toast.makeText(this, "需要蓝牙权限: ${missingPermissions.joinToString()}", Toast.LENGTH_LONG).show()
            return
        }
        
        try {
            connectionStatus.value = "正在搜索设备..."
            
            val pairedDevices = bluetoothAdapter?.bondedDevices
            var neuroSkyDevice: BluetoothDevice? = null
            
            // 调试信息：显示所有已配对设备
            val deviceList = mutableListOf<String>()
            pairedDevices?.forEach { device ->
                val deviceName = device.name ?: "未知设备"
                val deviceAddress = device.address ?: "未知地址"
                deviceList.add("$deviceName ($deviceAddress)")
                
                // 扩展设备名称匹配逻辑，支持更多NeuroSky设备变体
                if (device.name?.let { name ->
                    name.contains("NeuroSky", ignoreCase = true) ||
                    name.contains("MindWave", ignoreCase = true) ||
                    name.contains("ThinkGear", ignoreCase = true) ||
                    name.contains("EEG", ignoreCase = true) ||
                    name.contains("Neuro", ignoreCase = true) ||
                    name.startsWith("MW", ignoreCase = true) ||
                    name.startsWith("TG", ignoreCase = true) ||
                    name.contains("Brain", ignoreCase = true) ||
                    name.startsWith("HR-", ignoreCase = true) ||  // 支持HR-开头的设备
                    name.contains("HR-S0C", ignoreCase = true)    // 特定支持HR-S0C系列设备
                } == true) {
                    neuroSkyDevice = device
                    return@forEach
                }
            }
            
            // 显示调试信息
            val debugMessage = if (deviceList.isEmpty()) {
                "没有找到任何已配对的蓝牙设备"
            } else {
                "已配对设备列表:\n${deviceList.joinToString("\n")}"
            }
            
            if (neuroSkyDevice == null) {
                connectionStatus.value = "未找到NeuroSky设备"
                Toast.makeText(this, "$debugMessage\n\n请确保NeuroSky设备已配对", Toast.LENGTH_LONG).show()
                return
            }
            
            // 保存当前设备用于重连
            currentDevice = neuroSkyDevice
            reconnectAttempts = 0
            
            connectToDevice(neuroSkyDevice)
            
        } catch (e: Exception) {
            connectionStatus.value = "初始化错误: ${e.message}"
            Toast.makeText(this, "初始化错误: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
    
    private fun connectToDevice(device: BluetoothDevice) {
        if (isReconnecting.value) return
        
        connectionStatus.value = "正在连接 ${device.name}..."
        
        // 在后台线程中连接
        Thread {
            try {
                // 先关闭之前的连接
                try {
                    inputStream?.close()
                    bluetoothSocket?.close()
                } catch (e: Exception) {
                    // 忽略关闭异常
                }
                
                val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
                bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid)
                
                // 设置连接超时
                bluetoothSocket?.connect()
                
                inputStream = bluetoothSocket?.inputStream
                
                runOnUiThread {
                    isConnected.value = true
                    connectionStatus.value = "已连接到 ${device.name}"
                    Toast.makeText(this@MainActivity, "连接成功！", Toast.LENGTH_SHORT).show()
                    reconnectAttempts = 0 // 重置重连次数
                }
                
                // 开始读取数据
                startDataReading()
                
            } catch (e: IOException) {
                handleConnectionError(e, device)
            } catch (e: SecurityException) {
                runOnUiThread {
                    connectionStatus.value = "权限错误: ${e.message}"
                    Toast.makeText(this@MainActivity, "权限错误: ${e.message}", Toast.LENGTH_LONG).show()
                }
            } catch (e: Exception) {
                handleConnectionError(e, device)
            }
        }.start()
    }
    
    private fun handleConnectionError(e: Exception, device: BluetoothDevice) {
        runOnUiThread {
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts++
                connectionStatus.value = "连接失败，正在重试 ($reconnectAttempts/$maxReconnectAttempts)..."
                
                // 延迟2秒后重连
                Thread {
                    Thread.sleep(2000)
                    if (!isConnected.value) {
                        connectToDevice(device)
                    }
                }.start()
            } else {
                connectionStatus.value = "连接失败: ${e.message}"
                Toast.makeText(this@MainActivity, "连接失败，已达到最大重试次数: ${e.message}", Toast.LENGTH_LONG).show()
                reconnectAttempts = 0
            }
        }
    }
    
    private fun startDataReading() {
        Thread {
            val buffer = ByteArray(1024)
            var consecutiveErrors = 0
            val maxConsecutiveErrors = 5
            
            while (isConnected.value) {
                try {
                    val bytesRead = inputStream?.read(buffer) ?: -1
                    
                    if (bytesRead == -1) {
                        // 连接已断开
                        throw IOException("连接已断开")
                    }
                    
                    if (bytesRead > 0) {
                        val data = ByteArray(bytesRead)
                        System.arraycopy(buffer, 0, data, 0, bytesRead)
                        neuroSkyParser.parseData(data)
                        consecutiveErrors = 0 // 重置错误计数
                    }
                    
                } catch (e: IOException) {
                    consecutiveErrors++
                    
                    if (consecutiveErrors >= maxConsecutiveErrors) {
                        runOnUiThread {
                            connectionStatus.value = "连接不稳定，尝试重连..."
                            isConnected.value = false
                        }
                        
                        // 尝试重连
                        currentDevice?.let { device ->
                            if (reconnectAttempts < maxReconnectAttempts) {
                                Thread.sleep(1000)
                                connectToDevice(device)
                            }
                        }
                        break
                    } else {
                        // 短暂等待后继续尝试
                        Thread.sleep(100)
                    }
                }
            }
        }.start()
    }
    
    private fun disconnect() {
        isConnected.value = false
        try {
            inputStream?.close()
            bluetoothSocket?.close()
        } catch (e: IOException) {
            // 忽略关闭异常
        }
        connectionStatus.value = "已断开连接"
    }
    
    @Composable
    fun NeuroSkyApp() {
        val scope = rememberCoroutineScope()
        
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 标题
            Text(
                text = "NeuroSky 脑电波监测",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(bottom = 16.dp)
            )
            
            // 连接状态
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "连接状态",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Medium
                    )
                    Text(
                        text = connectionStatus.value,
                        fontSize = 16.sp,
                        color = if (isConnected.value) Color.Green else Color.Red,
                        modifier = Modifier.padding(top = 8.dp)
                    )
                    
                    // 显示当前连接的设备信息
                    selectedDevice.value?.let { device ->
                        Text(
                            text = "设备: ${device.name} (${device.address})",
                            fontSize = 14.sp,
                            color = Color.Gray,
                            modifier = Modifier.padding(top = 4.dp)
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    if (!isConnected.value) {
                        Button(
                            onClick = {
                                scope.launch {
                                    withContext(Dispatchers.IO) {
                                        getAvailableDevices()
                                    }
                                }
                            }
                        ) {
                            Text("选择设备连接")
                        }
                    } else {
                        Button(
                            onClick = { disconnect() },
                            colors = ButtonDefaults.buttonColors(containerColor = Color.Red)
                        ) {
                            Text("断开连接")
                        }
                    }
                }
            }
            
            // 设备选择对话框
            if (showDeviceSelection.value) {
                DeviceSelectionDialog(
                    devices = availableDevices.value,
                    onDeviceSelected = { device ->
                        scope.launch {
                            withContext(Dispatchers.IO) {
                                connectToSelectedDevice(device)
                            }
                        }
                    },
                    onDismiss = {
                        showDeviceSelection.value = false
                        connectionStatus.value = "未连接"
                    }
                )
            }
            
            // 数据显示
            if (isConnected.value) {
                // 基础数据
                DataCard("基础数据") {
                    DataRow("注意力", attention.value, "%")
                    DataRow("冥想", meditation.value, "%")
                    DataRow("信号质量", 100 - poorSignal.value, "%")
                    DataRow("眨眼强度", blinkStrength.value, "")
                    DataRow("原始数据", rawValue.value, "")
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 脑电波数据
                DataCard("脑电波频段") {
                    DataRow("Delta (0.5-2.75Hz)", delta.value, "")
                    DataRow("Theta (3.5-6.75Hz)", theta.value, "")
                    DataRow("Low Alpha (7.5-9.25Hz)", lowAlpha.value, "")
                    DataRow("High Alpha (10-11.75Hz)", highAlpha.value, "")
                    DataRow("Low Beta (13-16.75Hz)", lowBeta.value, "")
                    DataRow("High Beta (18-29.75Hz)", highBeta.value, "")
                    DataRow("Low Gamma (31-39.75Hz)", lowGamma.value, "")
                    DataRow("Mid Gamma (41-49.75Hz)", midGamma.value, "")
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 测试用：数据接收日志
                DataCard("数据接收日志 (最近20条)") {
                    Column {
                        Text(
                            text = "数据包总数: ${dataPacketCount.value}",
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Medium,
                            modifier = Modifier.padding(bottom = 8.dp)
                        )
                        
                        if (lastDataTimestamp.value > 0) {
                            Text(
                                text = "最后接收时间: ${java.text.SimpleDateFormat("HH:mm:ss.SSS").format(java.util.Date(lastDataTimestamp.value))}",
                                fontSize = 12.sp,
                                color = Color.Gray,
                                modifier = Modifier.padding(bottom = 8.dp)
                            )
                        }
                        
                        dataReceiveLog.value.forEach { logEntry ->
                            Text(
                                text = logEntry,
                                fontSize = 10.sp,
                                color = Color.Gray,
                                modifier = Modifier.padding(vertical = 1.dp)
                            )
                        }
                    }
                }
            }
        }
    }
    
    @Composable
    fun DeviceSelectionDialog(
        devices: List<BluetoothDevice>,
        onDeviceSelected: (BluetoothDevice) -> Unit,
        onDismiss: () -> Unit
    ) {
        AlertDialog(
            onDismissRequest = onDismiss,
            title = {
                Text(
                    text = "选择蓝牙设备",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold
                )
            },
            text = {
                Column {
                    Text(
                        text = "请选择要连接的蓝牙设备：",
                        modifier = Modifier.padding(bottom = 16.dp)
                    )
                    
                    devices.forEach { device ->
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp)
                                .clickable { onDeviceSelected(device) },
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant
                            )
                        ) {
                            Column(
                                modifier = Modifier.padding(12.dp)
                            ) {
                                Text(
                                    text = device.name ?: "未知设备",
                                    fontSize = 16.sp,
                                    fontWeight = FontWeight.Medium
                                )
                                Text(
                                    text = device.address ?: "未知地址",
                                    fontSize = 14.sp,
                                    color = Color.Gray
                                )
                            }
                        }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = onDismiss) {
                    Text("取消")
                }
            }
        )
    }

    @Composable
    fun DataCard(title: String, content: @Composable () -> Unit) {
        Card(
            modifier = Modifier.fillMaxWidth()
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = title,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.padding(bottom = 12.dp)
                )
                content()
            }
        }
    }
    
    @Composable
    fun DataRow(label: String, value: Int, unit: String) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 4.dp),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(text = label)
            Text(
                text = "$value$unit",
                fontWeight = FontWeight.Medium
            )
        }
    }
    
    /**
     * 获取已配对的蓝牙设备列表
     * 用于让用户手动选择要连接的设备
     */
    private fun getAvailableDevices() {
        // 检查蓝牙适配器
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show()
            return
        }
        
        if (bluetoothAdapter?.isEnabled != true) {
            Toast.makeText(this, "请先开启蓝牙", Toast.LENGTH_SHORT).show()
            return
        }
        
        // 检查权限
        val requiredPermissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            listOf(
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.BLUETOOTH_SCAN
            )
        } else {
            listOf(
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN
            )
        }
        
        val missingPermissions = requiredPermissions.filter {
            ActivityCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }
        
        if (missingPermissions.isNotEmpty()) {
            Toast.makeText(this, "需要蓝牙权限: ${missingPermissions.joinToString()}", Toast.LENGTH_LONG).show()
            return
        }
        
        try {
            connectionStatus.value = "正在获取已配对设备..."
            
            val pairedDevices = bluetoothAdapter?.bondedDevices
            val deviceList = mutableListOf<BluetoothDevice>()
            
            pairedDevices?.forEach { device ->
                // 只添加有名称的设备到列表中
                if (!device.name.isNullOrBlank()) {
                    deviceList.add(device)
                }
            }
            
            if (deviceList.isEmpty()) {
                connectionStatus.value = "未找到已配对的蓝牙设备"
                Toast.makeText(this, "没有找到任何已配对的蓝牙设备，请先在系统设置中配对设备", Toast.LENGTH_LONG).show()
                return
            }
            
            // 更新设备列表并显示选择界面
            availableDevices.value = deviceList
            showDeviceSelection.value = true
            connectionStatus.value = "请选择要连接的设备"
            
        } catch (e: Exception) {
            connectionStatus.value = "获取设备列表错误: ${e.message}"
            Toast.makeText(this, "获取设备列表错误: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
    
    /**
     * 连接到用户选择的设备
     */
    private fun connectToSelectedDevice(device: BluetoothDevice) {
        selectedDevice.value = device
        showDeviceSelection.value = false
        
        // 保存当前设备用于重连
        currentDevice = device
        reconnectAttempts = 0
        
        connectToDevice(device)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        disconnect()
    }
}